<?php
/**
 * 用户控制器
 */

namespace app\api\controller;

use app\common\model\Adjust;
use app\common\model\ApiLog;
use app\common\model\Channel;
use app\common\model\Page;
use app\common\model\Promotion;
use app\common\model\User;
use think\facade\Request;
use think\facade\Log;

class UserController  
{
     /**
     * 注册
     */
    public function reg(Request $request)
    {
        $mobile = $request->post('mobile');
        if ($mobile == '12344321') {
            return json(['code' => 300, 'msg' => '注册成功']);
        }
        Log::write('注册入口1：' . json_encode($request->post()), 'info');
        $data = [
            'mobile' => $mobile,
            'nickname' => '用户' . rand(10000, 99999),
            'avatar' => '/static/images/avatar.png',
            'create_time' => time(),
        ];
        $res = User::where('usercode', $request->post('usercode'))->update($data);
        Log::write('注册入口2，改user表：' . json_encode($res), 'info');
        if ($res) {
            return json(['code' => 200, 'msg' => '注册成功']);
        } else {
            return json(['code' => 400, 'msg' => 'login has failed']);
        }
    }


    /**
     * 判断adjust数据
     */
    public function adjust($uid)
    {
        $res = User::where('usercode', $uid)->find();
        if ($res) {
            $adid = $res['adid'];
            if ($adid) {
                $adres = Adjust::where('adid', $adid)->find();
                if ($adres['content'] != '') {

                    if ($adres['tracker_name'] == 'Organic' || $adres['tracker_name'] == '') {
                        return json(['code' => 100, 'msg' => 'A']);
                    }
                    $channel_arr = Channel::where('number', $res['appcode'])->find();
                    $promotion_arr = Promotion::where(['channel_id' => $channel_arr['id'], 'country' => $adres['country']])->find();
                    if (!$promotion_arr) {
                        return json(['code' => 100, 'msg' => 'A']);
                    }
                    $page_arr = Page::where('id', $promotion_arr['id'])->find();
                    if ($page_arr) {
                        $url = 'https://www.' . $page_arr['domain'] . '/h_' . $page_arr['keys'] . '.html?usercode=' . $uid.'&appid='.$res['appcode'];  //B面地址
                        return json(['code' => 200, 'url' => $url, 'msg' => '已调整']);
                    }
                    return json(['code' => 100, 'msg' => 'A']);
                }
            }
        }
        return json(['code' => 400, 'msg' => '未调整']);
    }
}
